<?php

namespace app\index\controller;

use think\Controller;
use think\Model;

class User extends Controller
{
    public function login()
    {
        if (session('blog_user', '', 'blog')) {
            $this->success('您以登录,无需重复登录', url('index/index'));
        }
        return $this->fetch();
    }

    public function register()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (!captcha_check($data['VerificationCode'])) {
                $this->error('验证码不正确');
            }
            if ($data['password'] != $data['re_password']) {
                $this->error('俩次输入密码不正确');
            }
            //密码加密
            $data['code'] = mt_rand(100, 10000);
            $data['password'] = md5($data['password'] . $data['code']);
            try {
                $result = model('User')->add($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('注册成功', url('user/login'));
            } else {
                $this->error('注册失败');
            }

        } else {
            return $this->fetch();
        }
    }


    public function logincheck()
    {
        if (!request()->isPost()) {
            $this->error('提交不合法');
        }
        $data = input('post.');
        if (!captcha_check($data['VerificationCode'])) {
            $this->error('验证码输入有误请重新输入');
        }
        try {
            $result = model('User')->getUserByUsername($data['username']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if (md5($data['password'] . $result['code']) != $result['password']) {
            $this->error('用户名或密码不正确');
        }

        //成功
        model('User')->upDataById(['last_login_time' => time()], $result['id']);
        //名称  值（查找出来的） 前缀
        session('blog_user', $result, 'blog');
        $this->success('登录成功欢迎您', url('index/index'));

    }

    public function logout()
    {
        session(null, 'blog');
        $this->redirect(url('index/user/login'));
    }
}


